window.addEventListener("load", () => {
    $(function () {

        class Login {
            constructor() {

                this.username = $("#user_name");
                this.password = $("#password");
                this.login_btn = $("#btn_login");
                this.alert = $("#login-alert");

                this.bindEvent();
                this.usermsg = JSON.parse(sessionStorage.getItem("usermsg"));
                if (this.usermsg !== null) {
                    this.writeUserMsg();
                }
            }

            writeUserMsg() {
                this.username.val(this.usermsg.username);
                this.password.val(this.usermsg.password);
            }
            bindEvent() {
                this.login_btn.on("click", () => {
                    this.login();
                });
            }
            login() {
                var name = this.username.val();
                var psd = this.password.val();
                axios.post("http://127.0.0.1:8888/users/login", `username=${name}&password=${psd}`)
                    .then(
                        (res) => {
                            console.log(res);
                            switch (res.data.code) {
                                case 1:
                                    this.success(res.data);
                                    break;
                                default:
                                    this.error(res.data);
                                    break;
                            }
                        })

            }
            success(res) {
                console.log(123132132);
                this.alert.removeClass("alert-success alert-danger");
                this.alert.addClass("alert-success");
                this.alert.html("恭喜登陆成功稍后我们将为您跳转到首页");

                setTimeout(() => {

                    cookie("TOKEN", res.token);
                    cookie("ID", res.user.id);

                    location.href = "./index.html";
                }, 2000);
            }
            error(res) {
                console.log(123132132);

                this.alert.removeClass("alert-success alert-danger");
                this.alert.addClass("alert-danger");
                this.alert.html("抱歉登录失败 : " + res.message);

                setTimeout(() => {
                    this.alert.removeClass("alert-success alert-danger");

                }, 2000)
            }
        }

        new Login();
    })
});